const connections = require('../app/database')

class UserService {
    async create(user) {
        const { userName, password } = user
        const statement = `INSERT INTO user (name, password) VALUES (?, ?);`;
        await connections.execute(statement, [userName, password])
        const result = await this.getUserByName(userName)
        return result[0]
    }
    async getUserByName(name) {
        const statement = `SELECT * FROM user WHERE name = ?;`;
        const result = await connections.execute(statement, [name]);
        return result[0];
    }

    async getUserByID(id) {
        const statement = `SELECT * FROM user WHERE id = ?;`;
        const result = await connections.execute(statement, [id]);
        return result[0];
    }
    async getUserAvatar(id) {
        const statement = `SELECT * FROM avatar WHERE user_id = ?;`;
        const [result] = await connections.execute(statement, [id]);
        return result.pop();
    }
    async updateAvatarUrlById(avatarUrl, id) {
        const statement = `UPDATE user SET avatar_url = ? WHERE id = ?`;
        const result = await connections.execute(statement, [avatarUrl, id]);
        return result[0];
    }
}

module.exports = new UserService()